package com.lft01.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 面试题：两个线程，一个线程打印1-52，另一个线程打印字母A-Z，打印顺序为12A34B...5152Z，要求用线程间的通信。
 * Function: 		ADD FUNCTION.
 * Reason:   		ADD REASON.
 * Date             2020/6/6 15:13
 * <p>
 * Class Name:      PrintNumLetter
 * Package Name:    com.lft.thread
 *
 * @author Laifengting
 * @version 1.0.0
 * @since JDK 8
 */
public class PrintNumLetter {
	private String status = "num";
	private int no = 1;
	private char letter = 'A';
	Lock lock = new ReentrantLock();
	final Condition pNum = lock.newCondition();
	final Condition pLetter = lock.newCondition();
	
	public void printNum() {
		lock.lock();
		try {
			while (!status.equalsIgnoreCase("num")) {
				try {
					pNum.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int i = 0; i < 2; i++) {
				System.out.print(no++);
			}
			status = "letter";
			pLetter.signal();
		} finally {
			lock.unlock();
		}
	}
	
	public void printLetter() {
		lock.lock();
		try {
			while (!status.equalsIgnoreCase("letter")) {
				try {
					pLetter.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.print(letter++);
			status = "num";
			pNum.signal();
		} finally {
			lock.unlock();
		}
	}
}
